package com.media.selector.media

import android.database.Cursor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.Nullable
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.media.selector.BR
import com.media.selector.R
import com.media.selector.databinding.FragmentMediaBinding
import com.media.selector.media.adapter.MediaItemAdapter
import com.media.selector.media.listener.OnMediaFragmentListener
import com.media.selector.media.listener.OnMediaItemClickListener
import com.media.selector.media.model.AlbumMediaCollection
import com.media.selector.media.model.SelectedCollection
import com.media.selector.media.model.entity.AlbumEntity
import com.media.selector.media.model.entity.MediaEntity
import com.media.selector.widget.recycler.MediaGridDecoration
import com.media.selector.widget.recycler.MediaGridLayoutManager

/**
 * date        ：2020/5/11
 * author      ：蒙景博
 * description ：
 */
class MediaFragment: Fragment(), AlbumMediaCollection.AlbumMediaCallbacks, OnMediaItemClickListener {

    companion object {
        fun with() = MediaFragment()
    }

    private var isNeedReload = true

    private lateinit var mBinding: FragmentMediaBinding
    private var mOnMediaFragmentListener: OnMediaFragmentListener? = null
    private val mAlbumMediaCollection by lazy { AlbumMediaCollection(requireActivity()) }
    private val mSelectedCollection by lazy { SelectedCollection(requireContext()) }
    private val mMediaAdapter by lazy { MediaItemAdapter(mSelectedCollection) }
    private val mCurrentAlbumAllMedia = ArrayList<MediaEntity>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(requireContext()), R.layout.fragment_media, container, false)
        mBinding.lifecycleOwner = this
        mBinding.setVariable(BR.data, this)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mBinding.mediaRecycler.layoutManager =
            MediaGridLayoutManager(
                requireContext(),
                4
            )
        val mSpacing = resources.getDimensionPixelSize(R.dimen.media_grid_spacing)
        mBinding.mediaRecycler.addItemDecoration(
            MediaGridDecoration(
                4,
                mSpacing,
                false
            )
        )
        mBinding.mediaRecycler.adapter = mMediaAdapter
        mMediaAdapter.setOnMediaItemClickListener(this)
        mAlbumMediaCollection.onCreate(this)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mSelectedCollection.onCreate(savedInstanceState)
        isNeedReload = true
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mSelectedCollection.onSaveInstanceState(outState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mAlbumMediaCollection.onDestroy()
        isNeedReload = true
    }

    fun loadMedia(album: AlbumEntity) {
        mAlbumMediaCollection.loadMedia(album)
        isNeedReload = true
    }

    override fun onAlbumMediaLoad(cursor: Cursor?) {
        refreshMediaData(cursor)
    }

    override fun onAlbumMediaReset() {
        refreshMediaData(null)
    }

    private fun refreshMediaData(cursor: Cursor?){
        if (isNeedReload) {
            val mMedias = mutableListOf<MediaEntity>()
            cursor?.use {
                while (it.moveToNext()) {
                    mMedias.add(MediaEntity.valueOf(it))
                }
            }
            mMediaAdapter.notifyAdapterChanged(mMedias)
            mCurrentAlbumAllMedia.clear()
            mCurrentAlbumAllMedia.addAll(mMedias.filter { !it.isCapture() })
        }
    }

    fun setOnMediaFragmentListener(listener: OnMediaFragmentListener) {
        this.mOnMediaFragmentListener = listener
    }

    fun getSelectedMedias(): ArrayList<MediaEntity>? {
        return mSelectedCollection.getSelectedDataBundle().getParcelableArrayList(SelectedCollection.STATE_SELECTION)
    }

    override fun onTakePhoto() {
        isNeedReload = false
        mOnMediaFragmentListener?.onTakePhoto()
    }

    override fun onMediaClick(clickType: Boolean, position: Int) {
        isNeedReload = false
        mOnMediaFragmentListener?.onMediaClick(clickType, position, mSelectedCollection.getCurrentAlbumAllDataBundle(mCurrentAlbumAllMedia), mSelectedCollection.getSelectedDataBundle())
    }

    override fun onCheckedStateChanged() {
        mOnMediaFragmentListener?.onCheckedStateChanged(mSelectedCollection.getSelectedMediaSize())
    }

    fun syncSelectedBundle(@Nullable result: Bundle?) {
        mSelectedCollection.syncSelectedMedias(result)
        mMediaAdapter.notifyDataSetChanged()
        mOnMediaFragmentListener?.onCheckedStateChanged(mSelectedCollection.getSelectedMediaSize())
    }
}